package com.gitlab.lucky.weixin.service;

import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.redis.RedisService;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-08 19:34
 **/
@Service
public class WeixinGzhAsyncService {
    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinGzhAsyncService.class);
    @Autowired
    private WeixinGzhMsgService weixinGzhMsgService;
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private WeixinUtil weixinUtil;
    @Autowired
    private RedisService redisService;

    /**
     * 返回邀请海报
     *
     * @param openId
     * @return
     */
    @Async
    public void getQRCode(String openId, Integer platform, String bjUrl) {
        LOGGER.info("返回邀请海报:{},{},{}",openId,platform,bjUrl);
        Object mediaId = redisService.get(Constant.MEDIA_ID + openId + "_" + platform);
        if (mediaId == null) {
            //通过openId生成的二维码链接
            String imageUrl = weixinGzhUserService.getTicket(openId, platform);
            LOGGER.info(imageUrl);
            try {
                //合并底图和二维码图片
                File file = weixinGzhUserService.inviteQRCodeImage(imageUrl, bjUrl);
                //将邀请图片上传至微信，返回媒体文件id
                mediaId = weixinUtil.uploadMedia(file, platform).getString(Constant.MEDIA_ID_STR);
                //2天过期
                redisService.set(Constant.MEDIA_ID + openId + "_" + platform, mediaId.toString(), Constant.MEDIA_ID_TIMEOUT);
            } catch (Exception e) {
                LOGGER.error("error", e);
            }
        }
        weixinGzhMsgService.resultServerImage(openId, mediaId.toString(), platform);
    }
}
